const { AbilityBuilder, Ability } = require("@casl/ability");
class Work {
  constructor(attr) {
    Object.assign(this, attr);
  }
}
const adminUser = { id: 1, role: "admin" };
const vipUser = { id: 2, role: "vip" };
const nomorUser = { id: 3, role: "nomor" };
const vipWork = new Work({ owner: 2 });
const nomorWork = new Work({ owner: 3 });
function defineAbility(user) {
  const { can, cannot, build } = new AbilityBuilder(Ability);
  if (user.role === "admin") {
    can("manage", "all");
  } else if (user.role === "vip") {
    can("download", "Work");
  }
  if (user.role === "nomor" || user.role === "vip") {
    can("read", "Work");
    can("update", "Work", { owner: user.id });
    can("delete", "Work", { owner: user.id });
  }
  return build();
}

const role = defineAbility(nomorUser);
console.log(role.can("read", "Work"));
console.log(role.can("download", "Work"));
console.log(role.can("delete", vipWork));
console.log(role.can("delete", nomorWork));
console.log(role.can("update", vipWork));
console.log(role.can("update", nomorWork));
